# coding: utf-8

import tornado
import datetime
from bson import ObjectId
from handlers.base import BaseHandler

class HealthPlanHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        # 获取用户健康计划的列表页
        if 'rid' in self.request.arguments:
            rid = self.get_query_argument('rid')
        else:
            self.response_msg(400, '参数错误')
            return
        try:
            # 获取role添加的健康计划
            role = yield self.db.HMRoles.find_one({'_id': ObjectId(rid)},{'_id':0,'healthPlan':1})
            if role:
                count = len(role['healthPlan'])
            else:
                count = 0
            #先查询所有的数据
            allPlan = self.db.HMHealthPlans.find({},{'_id':1,"logo":1,"title":1,"cycle":1,"completeLimitDays":1,"shortContent":1}).sort('sort',1)
            allPlans = []
            while(yield allPlan.fetch_next):
                tempObj = allPlan.next_object()
                tempObj['objectId'] = str(tempObj['_id'])
                del tempObj['_id']
                if count > 0 and tempObj['objectId'] in role['healthPlan']:
                    tempObj['isChecked'] = True
                else:
                    tempObj['isChecked'] = False
                allPlans.append(tempObj)
            #根据用户的count信息,组织数据
            self.response_msg(200, '获取健康计划成功', allPlans)
        except Exception as err:
            self.response_msg(201, '获取健康计划失败')


    #添加或删除健康计划
    @tornado.gen.coroutine
    def post(self):
        try:
            rid = self.get_argument('rid')
            pid = self.get_argument('pid')
            type = self.get_argument('type')
        except Exception as e:
            self.response_msg(400, '请求参数错误')
            return
        try:
            #添加记录到用户角色信息表
            if type == 'add':
                res = yield self.db.HMRoles.update({'_id':ObjectId(rid)},{'$addToSet':{'healthPlan':pid}})
            else:
                res = yield self.db.HMRoles.update({'_id':ObjectId(rid)},{"$pull":{'healthPlan':pid}})
            if res['updatedExisting']:
                self.response_msg(200,"修改健康计划成功")
            else:
                self.response_msg(201,"修改计划失败")
        except Exception as e:
            self.response_msg(400, '修改失败')



class HealthPlanDetail(BaseHandler):
    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        try:
            if 'pid' in self.request.arguments:
                pid = self.get_query_argument('pid')
            else:
                self.response_msg(200, '参数错误')
                return
        except Exception as e:
            self.response_msg(101,"获取参数失败")

        try:
            plan_detail = yield self.db.HMHealthPlans.find_one({'_id': ObjectId(pid)})
            if plan_detail:
                plan_detail['objectId'] = str(plan_detail['_id'])
                del plan_detail['_id']
                if plan_detail:
                    plan_detail['created_at'] = plan_detail['created_at'].strftime('%Y-%m-%d %H:%I:%S')
                    self.response_msg(200, '详情获取成功', plan_detail)
                else:
                    self.response_msg(400, '没有对应的健康计划')
            else:
                self.response_msg(400, '没有对应的健康计划')
        except Exception as e:
            print(e)
            self.response_msg(400, '查询出错')


class HealthPlanJoined(BaseHandler):
    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        if 'rid' in self.request.arguments:
            rid = self.get_query_argument('rid')
        else:
            self.response_msg(200, '参数错误')
            return
        try:
            # 获取role添加的健康计划
            role = yield self.db.HMRoles.find_one({'_id': ObjectId(rid)},{'_id':0,'healthPlan':1})
            if role:
                count = len(role['healthPlan'])
            else:
                count = 0
            #如果没有数据,则直接返回空
            if count == 0:
                self.response_msg(200, '用户还没有加入健康计划')
            else:
                idList = []
                for pid in role['healthPlan']:
                    idList.append(ObjectId(pid))
                #然后获取plan的相关信息
                plan_list = self.db.HMHealthPlans.find({'_id':{'$in':idList}},{'_id':1,'title':1,'logo':1})
                results = []
                while(yield plan_list.fetch_next):
                    planObj = plan_list.next_object()
                    planObj['objectId'] = str(planObj['_id'])
                    count = yield self.db.HMRolesPlanCheck.find({'role': rid, 'plan': str(planObj['_id'])},
                                                                {'created_at': {'$gt': datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)}}).count()
                    if count:
                        planObj['isChecked'] = True
                    else:
                        planObj['isChecked'] = False
                    del planObj['_id']
                    results.append(planObj)
                #返回数据
                self.response_msg(200, '健康计划如下', results)
        except Exception as e:
            self.response_msg(400, '获取数据失败')